/* eslint-disable no-undef,array-callback-return,no-trailing-spaces,no-unreachable,no-unused-vars,object-shorthand,prefer-destructuring */
/**
 * Created by mar105 on 2017-11-14.
 */
import React, { Component } from 'react';
import fetch from 'dva/fetch';
import { Layout, Spin, Modal, message } from 'antd';
import FastFilter from '../../components/Common/FastFilter/FastFilter';
import MergeTable from '../../components/Common/MergeTable/MergeTable';
import Toolbar from '../../components/Common/ToolBar/ToolBar';
// import Tree from '../../components/Common/Tree/Tree';
import styles from '../../index.less';
import baseHigher from './baseHigher';
import * as commonConfig from '../../utils/config';
import * as commonUtils from '../../utils/utils';
import * as commonFunc from './commonFunc';

const { Header, Content } = Layout;
const { confirm } = Modal;

class CommonList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      btnData: commonConfig.btnData, /* 工具栏按钮 */
      masterConfig: { sId: '' }, // 主表 + 从表 配置
      masterData: [],
      filterCondition: [],
      selectedRowKeys: [],
      sTabId: '', /* Tab页ID用于双击增加新Tab页面时候判断是由哪个父页面来的，防止出现页面多个commonList时候双击导致多个标签页出现BUG */
      sFilterOrderBy: {},
      bFilter: [],
      formData: [],
      pageSize: '',
      pages: {},
    };
  }

  componentWillReceiveProps(nextProps) {
    const { dataList } = nextProps.content;
    const { formData } = nextProps;
    if (this.state.formData.length === 0) {
      this.setState({ formData });
    }
    const {
      currentIndex, refresh, sDataListTabId, sParentId, formRoute, urlData, paneType, checkedId, disabled, componentName, sFilterOrderBy, bFilter, pageSize, pages, sListFormmasterId, currentData, newKey,
    } = dataList;
    if (urlData !== undefined && Object.keys(urlData).length > 0 && paneType !== undefined && paneType !== '' && nextProps.sTabId === sParentId) {
      const paneKey = new Date().getTime().toString();
      const pane = {
        refresh: refresh,
        copyToData: dataList.copyToData !== undefined ? dataList.copyToData : {}, /* 复制到数据 */
        title: urlData.sMenuName,
        route: urlData.sName,
        sModelsType: urlData.sModelType,
        formId: urlData.sId,
        checkedId,
        disabled,
        key: paneKey,
        sFilterOrderBy,
        bFilter,
        pageSize,
        pages,
        sListFormmasterId,
        currentData,
        newKey,
        currentIndex,
      };

      this.props.onAddPane(pane);
    }
    if (nextProps.sTabId === sDataListTabId &&
      nextProps.formRoute === formRoute &&
      nextProps.formData.length > 0 && this.state.masterConfig.sId === '') {
      const masterConfig = commonFunc.getTableConfig('CommonList', nextProps.formData);
      this.setState({ masterConfig, sTabId: nextProps.sTabId });
    }
    if (nextProps.sTabId === sDataListTabId && componentName === 'CommonList') {
      this.setState({ masterData: dataList.urlData });
    }
  }

  saveFilter(filterCondition) {
    const { sTabId, dispatch } = this.props;
    const componentName = 'CommonList';
    this.setState({ filterCondition });
    const dataList = { sDataListTabId: sTabId, componentName, returnType: 'isGetData' };
    dispatch({ type: 'content/setDataList', payload: { dataList } });
  }

  // saveFastFilter(filterCondition) {
  //   const { sTabId, dispatch } = this.props;
  //   const componentName = 'treeCommonList';
  //   setTimeout(() => {
  //     this.saveFilter(filterCondition);
  //     const dataList = { sDataListTabId: sTabId, componentName, returnType: 'isSearch' };
  //     dispatch({ type: 'content/setDataList', payload: { dataList } });
  //   });
  // }

  routeName(obj) {
    const { dispatch } = this.props;
    const { masterData } = this.state;
    const sTabId = new Date().getTime().toString(); /* Tab标签Id */
    dispatch({
      type: 'content/getUrlData',
      payload: {
        refresh: obj.refresh, /*   刷新方法   */
        url: obj.sNameUrl,
        sTabId,
        sParentId: this.state.sTabId,
        urlDataType: 'newPane',
        checkedId: obj.newsId,
        disabled: obj.disabled,
        sFilterOrderBy: obj.sFilterOrderBy,
        bFilter: obj.bFilter,
        pageSize: commonConfig.pageSize,
        pages: obj.pages,
        currentData: obj.currentData,
        sListFormmasterId: this.state.masterConfig.sId,
        newKey: obj.newKey,
        currentIndex: obj.currentIndex,
      },
    });
  }
  /* 新增 */
  handleAdd= () => {
    const { dispatch } = this.props;
    /* Tab标签Id */
    const paneKey = new Date().getTime().toString();
    const { masterConfig } = this.state;
    /* 窗体Id */
    let sActiveId = '';
    const obj = masterConfig.gdsconfigformslave.filter(item => (item.sName === 'picArr'));
    if (obj.length > 0) {
      if (obj[0].sName === 'picArr' && obj[0].sDropDownType === 'picArr') {
        [{ sActiveId }] = obj;
      }
    }
    const sNameUrl = `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`;
    dispatch({
      type: 'content/getUrlData',
      payload: {
        url: sNameUrl, sTabId: paneKey, urlDataType: 'newPane', disabled: false, sParentId: this.state.sTabId,
      },
    });
  };

  /* 打印 */
  /* handlePrint = () => {
    const { token } = this.props.app;
    const { formData, bFilter, sFilterOrderBy } = this.state;
    const sMainTableId = formData[0].sId;
    const queryFilter = {};
    formData.map((child) => {
      const sDataId = child.sId;
      if (bFilter.length > 0) {
        queryFilter[sDataId] = {
          bFilter,
        };
      }
      if (Object.keys(sFilterOrderBy).length > 0) {
        queryFilter[sDataId] = {
          sFilterOrderBy,
        };
      }
    });

    const { formId } = this.props;
    const url = `${config.server_host}printReport/getReport/${formId}?modelsId=${formId}`;
    const options = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        authorization: token,
      },
    };
    fetch(url, options).then(response => response.json()).then((json) => {
      if (json.code === 1) {
        const sReportId = json.dataset.rows[0].sId;
        let urlPrint = `${config.server_host}printReport/printPdf/${sReportId}?modelsId=${formId}&sMaintableId=${sMainTableId}&token=${encodeURIComponent(token)}`;
        if (queryFilter !== undefined && queryFilter !== '' && Object.keys(queryFilter).length > 0) {
          urlPrint = `${urlPrint}&queryFilter=${encodeURIComponent(JSON.stringify(queryFilter))}`;
        }
        window.open(urlPrint);
      } else {
        message.error(json.msg);
      }
    });
  }; */

  /* 导出Excel */
  handleOut = () => {
    const { token } = this.props.app;
    const { bFilter, sFilterOrderBy } = this.state;
    const { masterConfig } = this.state;
    let url = `${commonConfig.server_host}excel/export/${masterConfig.sId}?sModelsId=${masterConfig.sParentId}&token=${token}`;
    if (bFilter !== undefined && bFilter !== '' && Object.keys(bFilter).length > 0) {
      url = `${url}&bFilter=${encodeURIComponent(JSON.stringify(bFilter))}`;
    }
    if (sFilterOrderBy !== undefined && sFilterOrderBy !== '' && Object.keys(sFilterOrderBy).length > 0) {
      url = `${url}&sFilterOrderBy=${encodeURIComponent(JSON.stringify(sFilterOrderBy))}`;
    }
    window.open(url);
  };

  handleValue = (value) => {
    const { bFilter, sFilterOrderBy } = value;
    this.setState({ bFilter, sFilterOrderBy });
  };

  /* 删除 */
  handleDel = () => {
    const sSlaveIds = [];
    const sIds = [];
    for (const child of this.state.selectedRowKeys) {
      /* 由于存在统计项需要去除统计行，统计行不在选择时候过滤是由于会影响表格的正常全选反选功能，所以在此过滤 */
      if (child.indexOf('-') !== 0) {
        sSlaveIds.push(child);
      }
    }
    /* 列表KEY为从表ID,删除为根据主表ID进行,需遍历出主表ID */
    for (const v of this.state.masterData) {
      if (sSlaveIds.indexOf(v.key) > -1) {
        sIds.push(v.sId);
      }
    }
    const { token } = this.props.app;
    const { masterConfig } = this.state;
    const { handleRefresh } = this;
    const sTableName = masterConfig.sTbName;
    confirm({
      title: '确定要删除?',
      onOk() {
        const value = {
          data: {
            sMasterTable: `${sTableName}`,
            sId: sIds,
            sSlaveTable: 'commonList',
          },
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${commonConfig.server_host}business/delMasSlaBusinessData?sModelsId=${masterConfig.sParentId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            handleRefresh();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  /* 作废 */
  handleInvalid = () => {
    const sIds = [];
    for (const child of this.state.selectedRowKeys) {
      /* 由于存在统计项需要去除统计行，统计行不在选择时候过滤是由于会影响表格的正常全选反选功能，所以在此过滤 */
      if (child.indexOf('-') !== 0) {
        sIds.push(child.substring(0, child.indexOf('-')));
      }
    }
    const { token } = this.props.app;
    const { masterConfig } = this.state;
    const { handleRefresh } = this;
    const sTableName = masterConfig.sTbName;
    confirm({
      title: '确定要作废?',
      onOk() {
        const value = {
          sTableName: `${sTableName}`,
          sId: sIds,
          handleType: 'toVoid',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${commonConfig.server_host}checkModel/updatebInvalid?sModelsId=${masterConfig.sParentId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            handleRefresh();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  /* 取消作废 */
  handleCancelInvalid = () => {
    const sIds = [];
    for (const child of this.state.selectedRowKeys) {
      /* 由于存在统计项需要去除统计行，统计行不在选择时候过滤是由于会影响表格的正常全选反选功能，所以在此过滤 */
      if (child.indexOf('-') !== 0) {
        sIds.push(child.substring(0, child.indexOf('-')));
      }
    }
    const { token } = this.props.app;
    const { masterConfig } = this.state;
    const { handleRefresh } = this;
    const sTableName = masterConfig.sTbName;
    confirm({
      title: '确定要取消作废?',
      onOk() {
        const value = {
          sTableName: `${sTableName}`,
          sId: sIds,
          handleType: 'cancel',
          sClientType: '1',
        };
        const options = {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            authorization: token,
          },
          body: JSON.stringify(value),
        };
        const url = `${commonConfig.server_host}checkModel/updatebInvalid?sModelsId=${masterConfig.sParentId}`;
        fetch(url, options).then(response => response.json()).then((json) => {
          if (json.code === 1) {
            message.success(json.msg);
            handleRefresh();
          } else {
            message.error(json.msg);
          }
        });
      },
      onCancel() {},
    });
  };
  /* 表格选择行ID-目前只支持一个表格 */
  handleSelectedRowKeys = (selectedRowKeys) => {
    this.setState({ selectedRowKeys });
  };

  /* 刷新 */
  handleRefresh = () => {
    const { dispatch } = this.props;
    const { masterConfig } = this.state;
    const sTabId = this.props.app.panes[1].key;
    const mainDataUrl = `${commonConfig.server_host}business/getBusinessDataByFormcustomId/${masterConfig.sId}?sModelsId=${masterConfig.sParentId}`;
    const value = {
      bFilter: this.props.filterCondition,
      pageNum: 1,
      pageSize: commonConfig.pageSize,
    };
    dispatch({
      type: 'content/getUrlPostData',
      payload: {
        url: mainDataUrl, sTabId, componentName: 'CommonList', value, formRoute: '/commonList', returnType: 'data',
      },
    });
  };

  handleCopyTo = (name, sActiveId, config) => {
    const { dispatch } = this.props;
    const { masterData } = this.state;
    const copyTo = {};
    const copyToConfig = config;
    const copyToData = masterData.filter(item => commonUtils.isNotEmptyArr(this.state.selectedRowKeys) && this.state.selectedRowKeys.includes(item.key));
    copyTo.name = name;
    copyTo.config = copyToConfig;
    copyTo.masterData = copyToData[0];
    copyTo.slaveData = copyToData;
    dispatch({
      type: 'content/onRouter',
      payload: {
        url: `${commonConfig.server_host}gdsmodule/getGdsmoduleById/${sActiveId}?sModelsId=${sActiveId}`, /*   接口地址   */
        copyTo,
      },
    });
    // const { dispatch } = this.props;
    // const vConfig = value;
    // /* 复制过去的主表数据 */
    // let masterData = {};
    // /* 复制过去的从表数据 */
    // let masterSlaveData = [];
    // /* 表数据 */
    // const dataList = this.state.masterData;
    // /* 复制到必须进行勾选，如果没有勾选则不进行复制到功能 */
    // const sSlaveIds = [];
    // for (const child of this.state.selectedRowKeys) {
    //   if (child.indexOf('-') !== 0) {
    //     const selectLine = dataList.filter(item => child.indexOf(item.key) > -1);
    //     if (selectLine && selectLine.length > 0) {
    //       sSlaveIds.push(selectLine[0].sSlaveId);
    //     }
    //   }
    // }
    // if (vConfig.length > 0 && sSlaveIds.length > 0) {
    //   const result = commonFunc.getListCopyData(vConfig, dataList, sSlaveIds, this.state.masterConfig);
    //   if (result.errorName !== '') {
    //     message.error(`${result.errorName}数据不一致!`);
    //   } else {
    //     ({ masterData } = result);
    //     ({ masterSlaveData } = result);
    //     if (utils.isNotEmptyArr(masterSlaveData)) {
    //       for (const each of masterSlaveData) {
    //         each.sId = utils.createSid();
    //       }
    //     }
    //     dispatch({
    //       type: 'content/onRouter',
    //       payload: {
    //         url: `${config.server_host}gdsmodule/getGdsmoduleById/${activeId}?sModelsId=${activeId}`, /*   接口地址   */
    //         copyTo: { masterData, slaveData: masterSlaveData }, /*   复制到数据   */
    //         sParentId: this.state.sTabId, /*   父页面编号   */
    //       },
    //     });
    //   }
    // }
  };

  handleRoute = (payload) => {
    this.props.dispatch({
      type: 'content/onRouter',
      payload,
    });
  };

  render() {
    const { pageLoading } = this.props;
    return (
      <Spin spinning={pageLoading}>
        {pageLoading ? '' :
        <Layout id="commonList">
          <Header className={styles.header}>
            <Toolbar {...this.props} {...this.state} onAdd={this.handleAdd} onBtnDel={this.handleDel} onBtnInvalid={this.handleInvalid} onBtnCancelInvalid={this.handleCancelInvalid} onRefresh={this.handleRefresh} onCopyTo={this.handleCopyTo} onBtnOut={this.handleOut} componentName="toolCommonList" />
          </Header>
          <Layout className={styles.clayout}>
            <Content>
              <FastFilter {...this.props} {...this.state} componentName="fastCommonList" onSaveFilter={this.saveFilter.bind(this)} />
            </Content>
          </Layout>
          <Layout className={styles.clayoutBot}>
            {/* <Sider className={styles.sider}>
              <Tree {...this.props} {...this.state} componentName="treeCommonList" config={this.state.masterConfig} onSaveFilter={this.saveFilter.bind(this)} />
            </Sider> */}
            <Content className={styles.content}>
              <MergeTable
                {...this.props}
                {...this.state}
                componentName="CommonList"
                onSelectedRowKeys={this.handleSelectedRowKeys.bind(this)}
                config={this.state.masterConfig}
                onRouteName={this.routeName.bind(this)}
                onValue={this.handleValue.bind(this)}
                onRouter={this.handleRoute.bind(this)}
                onRefresh={this.handleRefresh.bind(this)}
              />
            </Content>
          </Layout>
        </Layout>}
      </Spin>
    );
  }
}

export default baseHigher(CommonList);
